﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MINERP.BLL.CustomerManage;
using Leadtools;
using Leadtools.Codecs;
using Leadtools.WinForms;
using Leadtools.Forms;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Views.Grid;
using System.Runtime.InteropServices;
using MINERP.ComControls.Extension;


namespace MINERP.CustomerManage.OrderInfo
{
    public partial class FrmOrderInfoDetail : Form
    {
        //参数
        private OrderInfoBLL bll = new OrderInfoBLL();
        private bool DisplayMode = false;                       //false列表 true缩略图
        private int orderStatus = -1;
        private RasterThumbnailBrowser browser = new RasterThumbnailBrowser();              //缩略图容器
        private DataTable photoDt = null;                       //照片集
        private DataTable flowDt = null;                        //流程集
        private DataTable recordDt = null;                      //停止恢复集
        //属性
        public OrderInfoBLL.OrderProductUser CurrentOrderInfo = null;                                               //当前产品的明细
        private static FrmOrderInfoDetail _instance;

        //win32 api
        [DllImport("shell32.dll ")]
        private static extern int ShellExecute(IntPtr hwnd, StringBuilder lpszOp, StringBuilder lpszFile, StringBuilder lpszParams, StringBuilder lpszDir, int FsShowCmd);

        public static FrmOrderInfoDetail GetInstance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new FrmOrderInfoDetail();
                }
                return _instance;
            }
            set
            {
                _instance = value;
            }
        }

        public FrmOrderInfoDetail()
        {
            InitializeComponent();

            gridViewPhotoInfo.ShowRowIndicator(50);

            gridViewProductProcess.ShowRowIndicator(50);

            gridView1.ShowRowIndicator(50);
        }

        private void FrmOrderInfoDetail_Load(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                //取产品所在订单的状态
                orderStatus = bll.GetOrderStatusByOrderProductId(CurrentOrderInfo.OrderProductId);
                //缩略图的拖曳操作
                browser.MouseDown += new MouseEventHandler(browser_MouseDown);
                browser.MouseMove += new MouseEventHandler(browser_MouseMove);
                browser.MouseUp += new MouseEventHandler(browser_MouseUp);
                browser.KeyDown += new KeyEventHandler(browser_KeyDown);
                browser.KeyUp += new KeyEventHandler(browser_KeyUp);
                SetDetail();
                photoDt = bll.GetPhotosByOrderProductId(CurrentOrderInfo.OrderProductId, orderStatus);
                SetPhotos(photoDt);
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //选择发生变化
        private void tabbbb_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            try
            {
                if (e.Page.Name == "tabPhoto")
                {
                    SetPhotos(photoDt);
                }
                else if (e.Page.Name == "tabFlow")
                {
                    flowDt = bll.GetFlowByOrderProductId(CurrentOrderInfo.OrderProductId, orderStatus);
                    SetFlows(flowDt);
                }
                else if (e.Page.Name == "tabRecord")
                {
                    recordDt = bll.GetStopRecordByOrderProductId(CurrentOrderInfo.OrderProductId);
                    SetStopRecord(recordDt);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        //照片列表与缩略图之间切换
        private void tsExchange_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                List<string> selectedPathes = new List<string>();       //选中的照片
                if (DisplayMode == false)                               //当前显示的是列表
                {
                    RasterCodecs.Startup();
                    RasterCodecs codecs = new RasterCodecs();
                    CodecsThumbnailOptions options = new CodecsThumbnailOptions();
                    options.LoadStamp = true;
                    options.MaintainAspectRatio = true;
                    options.Resample = true;
                    browser.Items.Clear();
                    browser.SelectionMode = RasterImageListSelectionMode.Multi;
                    int[] indexes = gridViewPhotoInfo.GetSelectedRows();
                    selectedPathes.Clear();
                    foreach (int index in indexes)
                    {
                        selectedPathes.Add(gridViewPhotoInfo.GetRowCellValue(index, "PicPath").ToString());
                    }
                    foreach (DataRow r in photoDt.Rows)
                    {
                        try
                        {
                            RasterImage img = codecs.ReadStamp(r["PicPath"].ToString(), 1);
                            if (img == null)
                            {
                                img = codecs.Load(r["PicPath"].ToString());         //缩略图不存在，就加载原图
                            }
                            RasterImageListItem item = new RasterImageListItem(img, 1, r["PhotoBarCode"].ToString());
                            string pp = r["PicPath"].ToString();
                            item.Tag = pp;
                            browser.Items.Add(item);
                            if (selectedPathes.Contains(pp))
                            {
                                item.Selected = true;
                                dragItems.Add(item);                //拖曳同步
                            }
                        }
                        catch
                        {
                            continue;
                        }
                    }
                    RasterCodecs.Shutdown();
                    if (splitContainer2.Panel2.Controls.Contains(gridPhotoInfo))
                    {
                        splitContainer2.Panel2.Controls.Remove(gridPhotoInfo);
                    }
                    browser.Dock = DockStyle.Fill;
                    splitContainer2.Panel2.Controls.Add(browser);
                    DisplayMode = true;
                }
                else
                {
                    if (splitContainer2.Panel2.Controls.Contains(browser))
                    {
                        RasterImageListItemCollection items = browser.SelectedItems;
                        foreach (RasterImageListItem item in items)
                        {
                            selectedPathes.Add(item.Tag.ToString());
                        }
                        splitContainer2.Panel2.Controls.Remove(browser);
                    }
                    splitContainer2.Panel2.Controls.Add(gridPhotoInfo);
                    gridViewPhotoInfo.ClearSelection();
                    for (int i = 0; i < gridViewPhotoInfo.RowCount; i++)
                    {
                        string path = gridViewPhotoInfo.GetRowCellValue(i, "PicPath").ToString();
                        if (selectedPathes.Contains(path))
                        {
                            gridViewPhotoInfo.SelectRow(i);
                        }
                    }
                    DisplayMode = false;
                }
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        #region 列表拖曳操作
        GridHitInfo downHitInfo = null;
        private void gridViewPhotoInfo_MouseDown(object sender, MouseEventArgs e)
        {
            downHitInfo = null;
            GridView view = sender as GridView;
            GridHitInfo info = view.CalcHitInfo(e.X, e.Y);
            if (e.Button == MouseButtons.Left && info.InRow && info.HitTest != GridHitTest.RowIndicator)
            {
                downHitInfo = info;
            }
        }

        private void gridViewPhotoInfo_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                GridView view = sender as GridView;
                if (e.Button == MouseButtons.Left && downHitInfo != null)
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(downHitInfo.HitPoint.X - dragSize.Width / 2, downHitInfo.HitPoint.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height);
                    if (!rec.Contains(e.X, e.Y))                    //执行拖曳操作
                    {
                        downHitInfo = null;
                        int[] indexes = gridViewPhotoInfo.GetSelectedRows();
                        string[] paths = new string[indexes.Length];
                        for (int i = 0; i < indexes.Length; i++)
                        {
                            paths[i] = gridViewPhotoInfo.GetRowCellValue(indexes[i], "PicPath").ToString();
                        }
                        DataObject data = new DataObject(DataFormats.FileDrop, paths);
                        DoDragDrop(data, DragDropEffects.Copy);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region 缩略图的拖曳操作
        Point ClickLocation;                 //鼠标按下的位置
        bool IsDrag = false;                    //有缩略图被选中，才执行拖曳操作 false无缩略图被选中 tru有缩略图被选中
        List<RasterImageListItem> dragItems = new List<RasterImageListItem>();
        bool IsCtrlDown = false;                //control键是否已按下
        bool IsShiftDown = false;               //shift键是否已按下

        void browser_KeyUp(object sender, KeyEventArgs e)
        {
            try
            {
                IsCtrlDown = false;
                IsShiftDown = false;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        void browser_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control)
                {
                    IsCtrlDown = true;
                }
                else if (e.Modifiers == Keys.Shift)
                {
                    IsShiftDown = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void browser_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                ClickLocation = new Point(e.X, e.Y);
                RasterImageListItem item = browser.HitTest(e.X, e.Y);
                if (item == null)
                {
                    IsDrag = false;
                    dragItems.Clear();
                }
                else
                {
                    if (dragItems.Contains(item))
                    {
                        foreach (RasterImageListItem tt in dragItems)
                        {
                            tt.Selected = true;
                        }
                        IsDrag = true;              //可以拖曳
                    }
                    else
                    {
                        if (IsCtrlDown == true)     //control键按下
                        {
                            dragItems.Add(item);
                        }
                        else if (IsShiftDown == true)   //shift键按下
                        {
                            dragItems.Clear();
                            dragItems.AddRange(browser.SelectedItems);
                        }
                        else
                        {
                            dragItems.Clear();
                            dragItems.Add(item);
                        }
                        IsDrag = true;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        void browser_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (IsDrag == true && e.Button == MouseButtons.Left)
                {
                    Size dragSize = SystemInformation.DragSize;
                    Rectangle rec = new Rectangle(ClickLocation.X - dragSize.Width / 2, ClickLocation.Y - dragSize.Height / 2, dragSize.Width, dragSize.Height);
                    if (!rec.Contains(e.X, e.Y))
                    {
                        List<string> photoPathes = new List<string>();
                        foreach (RasterImageListItem item in dragItems)
                        {
                            photoPathes.Add(item.Tag.ToString());
                        }
                        string[] pps = photoPathes.ToArray();
                        DataObject data = new DataObject(DataFormats.FileDrop, pps);
                        DoDragDrop(data, DragDropEffects.All);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        void browser_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                if (IsDrag == false && e.Button == MouseButtons.Left)                //选择操作
                {
                    RasterImageListItemCollection items = browser.SelectedItems;
                    dragItems.AddRange(items);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
        /*
        void browser_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                p = new Point(0, 0);
                if (e.Button == MouseButtons.Left)
                {
                    if (browser.SelectedItems != null && browser.SelectedItems.Count > 0)
                    {
                        IsDrag = true;
                    }
                    else
                    {
                        IsDrag = false;
                        return;
                    }
                    Point pp = new Point(e.X, e.Y);
                    if (pp.X != 0 && pp.Y != 0)
                    {
                        p = pp;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        void browser_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (e.Button == MouseButtons.Left)
                {
                    if (IsDrag == true)
                    {
                        if (browser.SelectedItems != null && browser.SelectedItems.Count > 0)
                        {
                            Size dragSize = SystemInformation.DragSize;
                            Rectangle rec = new Rectangle(new Point(p.X - dragSize.Width / 2, p.Y - dragSize.Height / 2), dragSize);
                            if (!rec.Contains(e.X, e.Y))
                            {
                                string[] paths = new string[browser.SelectedItems.Count];
                                RasterImageListItemCollection items = browser.SelectedItems;
                                List<string> pps = new List<string>();
                                foreach (RasterImageListItem item in items)
                                {
                                    pps.Add(item.Tag.ToString());
                                }
                                paths = pps.ToArray();
                                DataObject data = new DataObject(DataFormats.FileDrop, paths);
                                DoDragDrop(data, DragDropEffects.Copy);
                                p.X = 0;
                                p.Y = 0;
                                IsDrag = false;
                            }
                        }
                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "确定", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }*/
        #endregion

        //单击草组
        private void gridViewPhotoInfo_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            if (e.Column.FieldName == "PicPath")
            {
                //@"D:\Program Files\Adobe\Adobe Photoshop CS2\
                ShellExecute(IntPtr.Zero, new StringBuilder("open"), new StringBuilder("photoshop"),
                    new StringBuilder(gridViewPhotoInfo.GetRowCellValue(e.RowHandle,"PicPath").ToString()), new StringBuilder(string.Empty), 1);
                //System.Diagnostics.Process process = new System.Diagnostics.Process();
                //process.StartInfo.FileName = "Photoshop.exe";
                //process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
            }
        }

        //------------------------------------公共方法------------------------------------
        #region 设置照片基本信息
        /// <summary>
        /// 设置照片基本信息
        /// </summary>
        private void SetDetail()
        {
            lblInfoCode.Text = CurrentOrderInfo.OrderProductCode;
            lblInfoName.Text = CurrentOrderInfo.OrderProductName;
            lblCtmName.Text = CurrentOrderInfo.CtmName;
            lblPriority.Text = CurrentOrderInfo.OrderProductPriority.ToString();
            lblRemark.Text = CurrentOrderInfo.Remark;
        }
        #endregion

        #region 设置照片信息
        /// <summary>
        /// 设置照片信息
        /// </summary>
        /// <param name="dt"></param>
        private void SetPhotos(DataTable dt)
        {
            try
            {
                gridPhotoInfo.DataSource = dt;
                gridPhotoInfo.RefreshDataSource();
                if (dt != null)
                    lblPhotoCount.Text = dt.Rows.Count.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置流程
        /// <summary>
        /// 设置流程
        /// </summary>
        /// <param name="dt"></param>
        private void SetFlows(DataTable dt)
        {
            try
            {
                gridControlWorkFlowList.DataSource = dt;
                gridControlWorkFlowList.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 设置停止，恢复记录
        /// <summary>
        /// 设置停止，恢复记录
        /// </summary>
        /// <param name="dt"></param>
        private void SetStopRecord(DataTable dt)
        {
            try
            {
                gcStopRecord.DataSource = dt;
                gcStopRecord.RefreshDataSource();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion
    }
}
